﻿using System;
using Csla;
using BizControl.DalLinq;
using BizControl.Resources;

namespace BizControl.Library.BusinessObjects.Activities
{
  [Serializable()]
  public class ActivityLinks : BusinessListBase<ActivityLinks, ActivityLinkBO>
  {
    #region  Business Methods

    private ActivityBO _activity;

    public ActivityLinkBO AddLink(ActivityBO activity2, ActivityLinkType type)
    {
      ActivityLinkBO link = ActivityLinkBO.NewActivityLink(_activity, activity2, type);
      this.Add(link);
      return link;
    }

    public ActivityLinkBO this[Guid activity2SearchFor]
    {
      get
      {
        foreach (ActivityLinkBO link in this)
        {
          if (link.Activity2.Id == activity2SearchFor)
            return link;
        }
        return null;
      }
    }

    #endregion

    #region  Factory Methods

    internal static ActivityLinks NewActivityLinks(ActivityBO activity1)
    {
      return DataPortal.CreateChild<ActivityLinks>(activity1);
    }

    internal static ActivityLinks GetActivityLinks(ActivityLink[] data, ActivityBO activity1)
    {
      return DataPortal.FetchChild<ActivityLinks>(data, activity1);
    }

    private ActivityLinks()
    { }

    #endregion

    #region  Data Access

    private void Child_Create(ActivityBO activity1)
    {
      if (null == activity1) throw new ArgumentNullException(ExceptionsMessages.ActivityNullReference);
      _activity = activity1;
    }

    private void Child_Fetch(ActivityLink[] data, ActivityBO activity1)
    {
      if (null == activity1) throw new ArgumentNullException(ExceptionsMessages.ActivityNullReference);
      _activity = activity1;
      if (data == null) return;
      this.RaiseListChangedEvents = false;
      foreach (var child in data)
        Add(ActivityLinkBO.GetActivityLink(child, _activity));
      this.RaiseListChangedEvents = true;
    }

    #endregion
  }
}